<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="修改订单"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 50px);" :show-scrollbar="false">
			<view class="tab-content">
				<view style=" background-color:#EFEDE9;">
					<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
				</view>
				<u-form :model="form" ref="uForm" class="pl-3 pr-2">
					<u-form-item required label-width="230" label="上游服务商">
						<u-input :disabled="true" v-model="form.enterpriseName" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="230" label="产品/服务名称" prop="productServeName">
						<u-input v-model="form.productServeName" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="230" label="服务商名称" prop="serviceName">
						<u-input v-model="form.serviceName" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="230" label="服务介绍" prop="serviceIntroduce">
						<u-input type="textarea" height="100" v-model="form.serviceIntroduce" input-align="right" />
					</u-form-item>
					<view class="text-right text-BEBFE8">({{ wordCount }} / {{maxCharacters }})</view>
					<u-form-item required :required="true" label-width="180" label="服务介绍详情">
						<u-upload ref="uUpload" :file-list="fileList" :max-size="4 * 1024 * 1024"
							:form-data="{'biz':'temp'}" :header="header" @on-success="uploadSuccess"
							:action="getUploadUrl()" max-count="5">
						</u-upload>
					</u-form-item>
					<view class="font-12 text-FF0000">图片大小限制不能超过4MB,最多能上传五张图片</view>

					<u-form-item required label-width="230" label="服务价格(元)" prop="servicePrice">
						<u-input v-model="form.servicePrice" input-align="right" />
					</u-form-item>
					<!-- <u-form-item :label-style="labelStyle" label="服务流程">
						<u-input class="mr-3 " v-model="form.serviceFlow" input-align="right" />
					</u-form-item>
					<u-form-item :label-style="labelStyle" label="售后服务">
						<u-input class="mr-3 " v-model="form.serviceInform" input-align="right" />
					</u-form-item> -->

					<view style=" background-color:#EFEDE9;">
						<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">客户信息</view>
					</view>

					<!-- <u-form-item style="padding-right: 10px;" :label-style="labelStyle" label="涉农企业"
						prop="agricultureEnterpriseName">
						<u-input v-model="form.agricultureEnterpriseName" :type="type" input-align="right"
							:border="false" @click="showListCp = true" />
						<u-action-sheet :list="agricultureList" v-model="showListCp"
							@click="actionClickListCp"></u-action-sheet>
					</u-form-item> -->
					<u-form-item required required label-width="180" label="涉农企业" prop="productInformId">
						<u-input v-model="form.agricultureEnterpriseName" placeholder="请选择涉农企业" :type="type"
							input-align="right" :border="false" @click="showNatureBusinessHandler" />
						<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
							:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
					</u-form-item>

					<u-form-item required label-width="230" label="联系方式" prop="name">
						<u-input :disabled="true" placeholder="请先选择涉农企业" v-model="form.agricultureUserPhone"
							input-align="right" />
					</u-form-item>
					<view style=" background-color:#EFEDE9;">
						<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">订单信息</view>
					</view>
					<!-- <u-form-item :label-style="labelStyle" label="订单编号" prop="name">
						<u-input class="mr-3" :disabled="true" v-model="form.name" input-align="right" />
					</u-form-item> -->
					<u-form-item required label-width="230" label="订单时间" prop="createTime">
						<uni-calendar ref="calendarl" :start-date="currentDate" :insert="false" :lunar="true"
							@confirm="confirmName" :time-picker="true" />
						<view v-if="!selectedNameDate" class="text-999999 right-1-5 position-absolute"
							@click="openName">
						</view>
						<view class="right-1-5 position-absolute" @click="openName">{{formattedOrderTime}}
						</view>
					</u-form-item>

					<u-form-item required label-width="230" label="订单进度" prop="orderSchedule">
						<u-input v-model="form.orderSchedule" input-align="right" />
					</u-form-item>
					<u-form-item required label-width="230" label="订单评论" prop="orderEvaluation">
						<u-input v-model="form.orderEvaluation" input-align="right" />
					</u-form-item>
				</u-form>
			</view>

			<ferrButton title="修改订单" @click="editOrder"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	import $U from '@/common/free-lib/util.js';
	import $H from '@/common/free-lib/request.js';
	export default {
		components: {
			ferrButton,
			calendar
		},
		data() {
			return {
				rules: {
					productServeName: [{
						required: true,
						message: '产品/服务名称不能为空',
						trigger: ['change', 'blur'],
					}],
					servicePrice: [
						// {
						// 	required: true,
						// 	message: '服务价格不能为空',
						// 	trigger: ['change', 'blur'],
						// },
						{
							validator: (rule, value, callback) => {
								// 允许数字和最多两位小数，并且不小于零
								const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
								if (!reg.test(value)) {
									callback(new Error('请输入非负数字，可以有最多两位小数'));
								} else {
									callback();
								}
							},
							trigger: ['change', 'blur'],
						}
					],
					serviceInform: [{
						required: true,
						message: '售后服务不能为空',
						trigger: ['change', 'blur'],
					}],
					agricultureEnterpriseName: [{
						required: true,
						message: '涉农企业不能为空',
						trigger: ['change', 'blur'],
					}],
					orderTime: [{
						required: true,
						message: '订单时间不能为空',
						trigger: ['change', 'blur'],
					}],
					orderSchedule: [{
						required: true,
						message: '订单进度不能为空',
						trigger: ['change', 'blur'],
					}],
					orderEvaluation: [{
						required: true,
						message: '订单评价不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceName: [{
						required: true,
						message: '服务商名称不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceIntroduce: [{
						required: true,
						message: '服务介绍不能为空',
						trigger: ['change', 'blur'],
					}]
				},
				form: {
					id: "",
					enterpriseName: "",
					upperUserId: "",
					productServeName: "",
					servicePrice: "",
					serviceFlow: "",
					serviceInform: "",
					agricultureUserId: "",
					agricultureEnterpriseName: "",
					agricultureUserPhone: "",
					orderTime: "",
					orderSchedule: "",
					orderEvaluation: "",
					serviceName: "",
					serviceIntroduce: "",
					serviceIntroductionUrl: ''
				},
				value: '',

				type: 'select',
				selectedNameDate: null,
				agricultureList: [],
				valueListCp: '',
				showListCp: false,
				border: true,


				pages: {
					pageNo: 1,
					pageSize: 100,
					total: 0, // Total records
				},
				header: $H.getTokenHeader(),
				showNatureBusiness: false,
				natureBusinessList: [],
				
				maxCharacters: 200 
			};
		},
		onLoad(options) {
			this.queryAgricultureList();
			this.getOrderInfo(options.id);
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		created() {
			this.setCurrentDate();
		},
		computed: {
			fileList() {
				return Array.isArray(this.form.serviceIntroductionUrl) ? this.form.serviceIntroductionUrl : [];
			},
			formattedOrderTime() {
				if (!this.form.orderTime) return '';
				return this.form.orderTime.split(' ')[0];
			},
			wordCount() {
			  // 计算输入框中的字符数
			  return this.form.serviceIntroduce.length;
			}

		},
		methods: {
			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			showNatureBusinessHandler() {
				this.showNatureBusiness = true;
			},
			selectNatureBusiness(e) {
				this.form.agricultureEnterpriseName = this.natureBusinessList[e[0]].text
				this.form.agricultureUserId = this.natureBusinessList[e[0]].id;
				this.form.agricultureUserPhone = this.natureBusinessList[e[0]].phone;
			},



			openName() {
				this.$refs.calendarl.open();
			},
			confirmName(e) {
				this.selectedNameDate = e.fulldate;
				// 获取当前的日期
				const formattedDate = e.fulldate; // 只使用日期部分
				this.form.orderTime = formattedDate;

			},
			setCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份补齐两位数
				const day = now.getDate().toString().padStart(2, '0'); // 日期补齐两位数
				this.currentDate = `${year}-${month}-${day}`;
			},

			getOrderInfo(id) {
				uni.showLoading({
					title: '加载中'
				});
				$H.get(
					"/upper/upperMarketOrder/queryById", {
						id,
					}, {}
				).then(async (res) => {
					if (!res.result) {
						uni.showToast({
							title: "未查询到相关信息",
							icon: "none",
						});
						return;
					}
					this.form.id = res.result.id;
					this.form.orderType = res.result.orderType;
					this.form.orderEvaluation = res.result.orderEvaluation;
					this.form.orderSchedule = res.result.orderSchedule;
					this.form.orderTime = res.result.orderTime;
					this.form.serviceInform = res.result.serviceInform;
					this.form.serviceFlow = res.result.serviceFlow;
					this.form.servicePrice = res.result.servicePrice;
					this.form.serviceIntroduce = res.result.serviceIntroduce;
					this.form.serviceName = res.result.serviceName;
					this.form.productServeName = res.result.productServeName;
					this.form.upperUserId = res.result.upperUserId;
					this.form.agricultureUserId = res.result.agricultureUserId;
					await this.getAgricultureUserInfo(res.result.agricultureUserId);
					await this.getUpperUserInfo(res.result.upperUserId);
					if (res.result.serviceIntroductionUrl) {
						// Split the URLs and map each one to an object with the 'url' property
						this.form.serviceIntroductionUrl = res.result.serviceIntroductionUrl.split(',').map(
							url =>
							({
								url: this.getFullImageUrl(url)
							}));
					} else {
						this.form.serviceIntroductionUrl = [];
					}
					uni.hideLoading();
				}).catch(error => {
					console.error('请求出错', error); // 处理任何错误
					uni.showToast({
						title: "查询错误",
						icon: "none",
					});
					uni.hideLoading();
				})

			},

			async getAgricultureUserInfo(userId) {
				await $H.get(
					"/brand/user/queryById", {
						id: userId,
					}, {}
				).then((res) => {
					this.form.agricultureUserPhone = res.result.phone;
					this.form.agricultureEnterpriseName = res.result.enterpriseName;
				});
			},
			async getUpperUserInfo(userId) {
				await $H.get(
					"/brand/user/queryById", {
						id: userId,
					}, {}
				).then((res) => {
					this.form.enterpriseName = res.result.enterpriseName;
				});
			},
			queryAgricultureList() {
				uni.showLoading({
					title: '加载中'
				});

				$H.get('/brand/user/selectUserList', {
						userType: 'AGRICULTURE',
						...this.pages
					}, {})
					.then(res => {
						uni.hideLoading();
						if (res.result.length == 0) {
							uni.showToast({
								title: '涉农列表为空',
								icon: 'success'
							});
							return;
						}
						for (let i = 0; i < res.result.length; i++) {
							res.result[i]['text'] = res.result[i]['enterpriseName'];
						}
						console.log("res.result", res.result)
						this.natureBusinessList = res.result;
					})
					.catch(error => {
						console.error('请求出错', error); // 处理任何错误  
						uni.hideLoading();
					});
			},
			editOrder() {
				let files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				});

				// Check if no files are uploaded
				if (files.length === 0) {
					this.form.serviceIntroductionUrl = ""; // Set default image URL or empty string
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '加载中'
						});
						if (this.form.orderTime) {
							const date = new Date(this.form.orderTime);
							this.form.orderTime =
								`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} 00:00:00`;
						}
						// Get the uploaded file URLs
						const uploadedFileUrls = files
							.filter(file => file.response?.message)
							.map(file => file.response.message);

						// Concatenate default image URLs with uploaded file URLs
						let allFileUrls = [];
						if (Array.isArray(this.form.serviceIntroductionUrl)) {
							allFileUrls = this.form.serviceIntroductionUrl.map(defaultImage => defaultImage.url);
						}
						allFileUrls = allFileUrls.concat(uploadedFileUrls).join(',');
						$H.post(
								"/upper/upperMarketOrder/upper/editOrder", {
									...this.form,
									serviceIntroductionUrl: allFileUrls
								}, {}
							).then((res) => {
								uni.hideLoading();
								if (res.success) {
									uni.showToast({
										title: '修改成功',
										icon: 'success',
										duration: 4000
									});
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									}, 4000);
								} else {
									uni.showToast({
										title: res.message || '修改失败',
										icon: 'none'
									});
								}
							})
							.catch(error => {
								uni.hideLoading();
								console.error('请求出错', error); // 处理任何错误  
								uni.showToast({
									title: '修改失败',
									icon: 'none'
								});
							});
					} else {
						uni.showToast({
							title: '请填写完整信息',
							icon: 'none'
						});
					}
				});
			}

		}

	};
</script>

<style>

</style>